package com.mobi.Survey;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.appbucks.sdk.AppBucksBanner;
import com.mobi.Survey.Exceptions.EmptyFieldException;
import com.mobi.Survey.controller.SurveyDetailPojo;
import com.mobi.Survey.controller.SurveyPojo;
import com.mobi.Survey.controller.SurveyResultPojo;
import com.mobi.Survey.controller.User;
import com.mobi.Survey.controller.WebServiceIO;
import com.mobi.Survey.model.AbstractTable;
import com.mobi.Survey.model.SurveyDetailTable;
import com.mobi.Survey.model.SurveyTable;
import com.mobi.Survey.uicomponents.ControlFactory;
import com.mobi.Survey.utils.Helper;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyDetailScreen.java This class is responsible for displaying survey
 * detail. user passes survey id for this class
 */
public abstract class AbstractDetailScreen extends AbstractScreen
{
	// Common Variables
	protected long surveyId;
	protected SurveyPojo survey;
	protected AppBucksBanner banner;
	protected Button btnSubmit;
	protected ImageView ivBgImage;
	protected View parent;

	protected List<SurveyDetailPojo> sdps;
	protected List<View> views = new ArrayList<View>();
	protected List<Object> viewVids = new ArrayList<Object>();

	protected List<String> videoUrls = new ArrayList<String>();
	protected List<Bitmap> bitmapsVids = new ArrayList<Bitmap>();
	protected List<String> imageUrls = new ArrayList<String>();

	/**
	 * if single screen button will be added other wise image view will be added
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// hideTitle = true;
		super.onCreate(savedInstanceState);

		final Intent intent = getIntent();

		if (intent != null)
		{
			final Bundle bundle = intent.getExtras();
			if (bundle != null)
			{
				surveyId = ((Long) bundle.get("data")).intValue();
				final SurveyTable sdTable = new SurveyTable(this);
				survey = sdTable.getSurveyWithDetail(this, surveyId);
				sdTable.closeDB();
			}

		}

		setTitle(survey.getSurveyDiscription());
		final String bgColor = survey.getbGColor();
		if (null != bgColor
				&& bgColor.length() > 0
				&& (null == survey.getbGImageUrl() || survey.getbGImageUrl()
						.length() == 0))
		{
			parent.setBackgroundColor(Color.parseColor("#" + bgColor));
		} else
		{
			parent.setBackgroundColor(Color.BLACK);
		}

		new LongTask().execute(surveyId);

		// Set Header View background
		showHeaderImage(User.getInstance().getDetailImage());

	}

	@Override
	protected void onStart()
	{

		super.onStart();
		if (User.getInstance().isShowAds()
				&& Helper.isNetworkAvailable(getBaseContext()) && adsEnabled)
		{
			if (banner.getVisibility() == View.GONE)
				banner.setVisibility(View.VISIBLE);
			banner.showAd();
		}
	}

	@Override
	protected void initUiVars()
	{
		btnSubmit = (Button) findViewById(R.id.btnSubmit);
		parent = findViewById(R.id.parent);
		ivBgImage = (ImageView) findViewById(R.id.ivBgImage);
		banner = (AppBucksBanner) findViewById(R.id.banner);
		headerImage = findViewById(R.id.headerImage);

	}

	/**
	 * creates controls dynamically on the base of survey detail data if survey
	 * type is single screen all controls are displayed other wise other
	 * controls are made invisible
	 */
	protected abstract void createViews();

	private void showDuplicateAnswerDialogue(String message)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message)
				.setCancelable(false)
				.setPositiveButton(Messages.RESUBMIT_ANSWER,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{

								new ResultSubmitTask().execute();

							}
						})
				.setNegativeButton(Messages.CANCEL,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{

							}
						});

		AlertDialog alert = builder.create();
		alert.show();
	}

	protected void btnClick(View vi)

	{

		if (vi.getId() == R.id.btnSubmit)
		{
			if (SurveyResultPojo.isNew(surveyId, AbstractDetailScreen.this) == 0)
			{
				new ResultSubmitTask().execute();
			} else
			{
				showDuplicateAnswerDialogue(Messages.ALREADY_ANSWERED);
			}
		}

	}

	/**
	 * 
	 * @param surveyDetailPojo
	 * @param view
	 *            <p>
	 *            If Survey Detail type was single screen we created Button for
	 *            Video and Image control so on user click we display image and
	 *            video in separate screen we also keep reference of our buttons
	 *            or image preview in a Collection to track user click
	 * 
	 */
	protected abstract void performActionOnVideoControl(
			SurveyDetailPojo surveyDetailPojo, View view);

	/**
	 * If single screen we will display button for image control other wise we
	 * will display image
	 * 
	 * @param surveyDetailPojo
	 * @param view
	 */
	protected abstract void performActionOnImageControl(
			SurveyDetailPojo surveyDetailPojo, View view);

	/**
	 * 
	 * @author Yahya Arshad Retrieve Image Survey detail data in background
	 *         after Retrieving create views on base of that data
	 */
	private class LongTask extends AsyncTask<Long, Integer, Object>
	{
		ProgressDialog progressDialog = null;

		protected Object doInBackground(Long... params)
		{
			long surveyId = params[0];
			AbstractTable at = new SurveyDetailTable(AbstractDetailScreen.this);
			sdps = ((SurveyDetailTable) at).getSurveyDetail(surveyId);
			for (SurveyDetailPojo sdp : sdps)
			{
				sdp.setSurvey(survey);

			}
			at.closeDB();
			SurveyResultPojo.writeSurveyResult(surveyId, sdps,
					AbstractDetailScreen.this);

			return null;

		}

		protected void onPostExecute(Object result)
		{

			super.onPostExecute(result);
			createViews();
			progressDialog.dismiss();
			progressDialog = null;

		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(AbstractDetailScreen.this,
						"", Messages.FETCHING_SURVEY_DETAIL);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

	protected abstract void onEmptyFieldException(int controlIndex);

	/**
	 * 
	 * Submit user result to server on ok response submitted survey data will be
	 * entered to users database too.
	 */
	private class ResultSubmitTask extends AsyncTask<Long, Integer, Boolean>
	{
		private ProgressDialog progressDialog = null;
		private String message;

		protected Boolean doInBackground(Long... params)
		{
			try
			{
				ControlFactory.getUserInputs(sdps, views);
				// If we are in debug mode we will not submit survey to server
				// so we simply return true to let survey commit in local db

				return WebServiceIO.submitResult(sdps, surveyId);

			} catch (final EmptyFieldException e)
			{
				message = e.getMessage();
				runOnUiThread(new Runnable()
				{

					@Override
					public void run()
					{
						onEmptyFieldException(e.getDataIndex());

					}
				});

				return false;
			} catch (Exception e)
			{
				message = Messages.SURVEY_CAN_NOT_SUBMIT;
				return false;
			}

		}

		protected void onPostExecute(Boolean response)
		{

			super.onPostExecute(response);
			if (response)
			{
				// delete if any survey result data already exist
				SurveyResultPojo.delete(surveyId, AbstractDetailScreen.this);
				SurveyResultPojo.commit(surveyId, sdps,
						AbstractDetailScreen.this);
				SurveyListScreen.reSynch = true;
				showLongToast(Messages.SURVEY_SUBMITTED);
				finish();

			} else
			{
				// In case of false response from server
				showAlert(message);
			}
			progressDialog.dismiss();
			progressDialog = null;

		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(AbstractDetailScreen.this,
						"", Messages.SUBMITTING_SURVEY);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

}
